<template>
    <div class="dashboard-container">
      <h1 class="dashboard-title">平台数据仪表盘</h1>
  
      <!-- 指标卡片 -->
      <div class="metric-grid">
        <div class="metric-card">
          <h3>总销售额</h3>
          <div class="metric-value"> {{ totalSales }}</div>
        </div>
        <div class="metric-card">
          <h3>总订单数</h3>
          <div class="metric-value">{{ totalOrders }}</div>
        </div>
        <div class="metric-card">
          <h3>待审用户</h3>
          <div class="metric-value">{{ pendingUsers }}</div>
        </div>
        <div class="metric-card">
          <h3>待审商品</h3>
          <div class="metric-value">{{ pendingProducts }}</div>
        </div>
      </div>
  
      <!-- 图表区域 -->
      <div class="chart-container">
        <div class="chart-card">
          <h3>销售趋势（最近30天）</h3>
          <div ref="salesChart" class="chart"></div>
        </div>
        <div class="chart-card">
          <h3>订单状态分布</h3>
          <div ref="statusChart" class="chart"></div>
        </div>
      </div>
  
      <!-- 热销商品 -->
      <div class="popular-products">
    <h3>热销商品 TOP10</h3>
    <el-table 
      :data="popularProducts" 
      style="width: 100%" 
      border
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column 
        prop="productName" 
        label="商品名称" 
        min-width="180"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span class="product-name">{{ row.productName }}</span>
        </template>
      </el-table-column>
      
      <el-table-column 
        label="封面图" 
        width="120" 
        align="center"
      >
        <template #default="{ row }">
          <div class="image-container">
            <img 
              :src="'http://localhost:8092'+row.cover" 
              class="product-cover" 
              alt="商品封面"
            />
          </div>
        </template>
      </el-table-column>
      
      <el-table-column 
        prop="salesCount" 
        label="销量" 
        width="120" 
        align="center"
      />
      
      <el-table-column 
        prop="totalAmount" 
        label="销售额" 
        width="150" 
        align="right"
      >
        <template #default="{ row }">
          <span class="money">¥ {{ row.totalAmount }}</span>
        </template>
      </el-table-column>
      
      <el-table-column 
        prop="category" 
        label="分类" 
        width="120" 
        show-overflow-tooltip
      />
    </el-table>
  </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  import axios from 'axios'
  
  // 图表容器引用
  const salesChart = ref(null)
  const statusChart = ref(null)
  
  // 响应式数据
  const totalSales = ref(0)
  const totalOrders = ref(0)
  const pendingUsers = ref(0)
  const pendingProducts = ref(0)
  const popularProducts = ref([])
  
  // 图表实例
  let salesChartInstance = null
  let statusChartInstance = null
  
  // 初始化流程
  onMounted(async () => {
    try {
      await fetchData()
      initCharts()
      updateCharts()
      window.addEventListener('resize', handleResize)
    } catch (error) {
      console.error('初始化失败:', error)
    }
  })
  
  // 获取数据
  const fetchData = async () => {
    try {
      const res = await axios.get('http://localhost:8092/order/admin/analyzePlatformData')
      const data = res.data.data
  
      // 基础指标
      totalSales.value = (data.totalSales || 0).toLocaleString('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
      totalOrders.value = (data.totalOrders || 0).toLocaleString()
      pendingUsers.value = data.pendingUsers || 0
      pendingProducts.value = data.pendingProducts || 0
  
      // 处理时间序列数据
      const timeSeries = {}
      if (data.timeSeries && Array.isArray(data.timeSeries)) {
        data.timeSeries.forEach(item => {
          timeSeries[item.day] = parseFloat(item.total) || 0
        })
      }
  
      // 处理状态分布
      const statusDistribution = {}
      if (data.statusDistribution && Array.isArray(data.statusDistribution)) {
        data.statusDistribution.forEach(item => {
          const status = statusToString(item.status) || '未知状态'
          statusDistribution[status] = item.count || 0
        })
      }
  
      // 处理热销商品
      popularProducts.value = (data.popularProducts || []).map(p => ({
        productId: p.product_id || 'N/A',
        productName: p.product_name || '未命名商品',
        cover: (p.images ? p.images.split(',')[0] : '/default-product.jpg'),
        salesCount: p.sales_count || 0,
        totalAmount: ((p.sales_count || 0) * (p.price || 0)).toFixed(2),
        category: p.category || '未分类'
      }))
  
      // 存储数据用于图表
      chartData.value = { timeSeries, statusDistribution }
  
    } catch (error) {
      console.error('数据获取失败:', error)
      // 设置默认数据防止图表崩溃
      chartData.value = {
        timeSeries: {},
        statusDistribution: {}
      }
    }
  }
  
  // 图表数据存储
  const chartData = ref({
    timeSeries: {},
    statusDistribution: {}
  })
  
  // 图表初始化
  const initCharts = () => {
    if (!salesChartInstance && salesChart.value) {
      salesChartInstance = echarts.init(salesChart.value)
    }
    if (!statusChartInstance && statusChart.value) {
      statusChartInstance = echarts.init(statusChart.value)
    }
  }
  
  // 更新图表
  const updateCharts = () => {
    if (!salesChartInstance || !statusChartInstance) return
  
    // 销售趋势图表
    const salesOption = {
      tooltip: {
        trigger: 'axis',
        formatter: '¥ {c}',
        axisPointer: { type: 'shadow' }
      },
      xAxis: {
        type: 'category',
        data: Object.keys(chartData.value.timeSeries),
        axisLabel: { rotate: 45 }
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '¥ {value}' }
      },
      series: [{
        data: Object.values(chartData.value.timeSeries),
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }]
    }
  
    // 状态分布图表
    const statusOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        type: 'pie',
        radius: '65%',
        data: Object.entries(chartData.value.statusDistribution).map(([name, value]) => ({
          name,
          value,
          itemStyle: {
            color: statusColor(name)
          }
        })),
        label: {
          formatter: '{b|{b}}\n{d}%',
          rich: { b: { fontWeight: 'bold' } }
        }
      }]
    }
  
    try {
      salesChartInstance.setOption(salesOption)
      statusChartInstance.setOption(statusOption)
    } catch (e) {
      console.error('图表更新失败:', e)
    }
  }
  
  // 状态颜色映射
  const statusColor = (status) => {
    const colors = {
      '待支付': '#FFB74D',
      '已支付': '#4FC3F7',
      '已发货': '#81C784',
      '已完成': '#64B5F6',
      '已取消': '#E57373'
    }
    return colors[status] || '#999'
  }
  
  // 状态转换
  const statusToString = (statusCode) => {
    const statusMap = {
      1: '待支付',
      2: '已支付',
      3: '已发货',
      4: '已完成',
      5: '已取消'
    }
    return statusMap[statusCode] || '未知状态'
  }
  
  // 窗口resize处理
  const handleResize = () => {
    salesChartInstance?.resize()
    statusChartInstance?.resize()
  }
  
  // 组件卸载清理
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    salesChartInstance?.dispose()
    statusChartInstance?.dispose()
  })
  </script>
  
  <style scoped>
  .dashboard-container {
    padding: 24px;
    max-width: 1400px;
    margin: 0 auto;
  }
  
  .dashboard-title {
    text-align: center;
    margin: 0 0 32px;
    font-size: 24px;
    color: #333;
  }
  
  .metric-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 32px;
  }
  
  .metric-card {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    transition: transform 0.3s;
  }
  
  .metric-card:hover {
    transform: translateY(-5px);
  }
  
  .metric-card h3 {
    margin: 0 0 12px;
    font-size: 16px;
    color: #666;
  }
  
  .metric-value {
    font-size: 24px;
    font-weight: 600;
    color: #409EFF;
  }
  
  .chart-container {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;
    margin-bottom: 32px;
  }
  
  .chart-card {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .chart-card h3 {
    margin: 0 0 20px;
    font-size: 18px;
    color: #333;
  }
  
  .chart {
    height: 400px;
  }
  
  .popular-products {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .popular-products h3 {
    margin: 0 0 20px;
    font-size: 18px;
    color: #333;
  }
  
  .product-cover {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
  }
  .popular-products {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow-x: auto;
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  padding: 4px;
}

.product-cover {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 4px;
  transition: transform 0.3s;
}

.product-cover:hover {
  transform: scale(1.05);
}

.product-name {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.money {
  font-family: 'Arial', sans-serif;
  color: #e6a23c;
  font-weight: 600;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .popular-products {
    padding: 16px;
  }
  
  .product-name {
    -webkit-line-clamp: 1;
  }
}   
  </style>